package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.behavior.IBehaviorFeign;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApCollectionService;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApCollection;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.ApThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {

    @Autowired
    private IBehaviorFeign behaviorFeign;

     @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        //1.判断参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.获取用户ID
        ApUser apUser = ApThreadLocalUtils.getUser();
        Integer userId = null;
        if(apUser!=null && apUser.getId()!=0){
            userId = apUser.getId();//获取正常登录用户的ID值
        }

        //3.根据用户ID和设备ID查询行为实体并判断是否存在
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdAndEquipmentId(userId, dto.getEquipmentId());
        if(apBehaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "行为实体不存在");
        }

        //4.查询收藏行为是否存在，如果不存在就创建
        ApCollection apCollection = getOne(Wrappers.<ApCollection>lambdaQuery().
                eq(ApCollection::getEntryId, apBehaviorEntry.getId()).
                eq(ApCollection::getArticleId, dto.getEntryId()).
                eq(ApCollection::getType, dto.getType()));

        if(apCollection==null){
            if(dto.getOperation()==1){ //数据不存在，如果取消收藏，则有问题
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "数据不存在，无法取消收藏");
            }
            apCollection = new ApCollection();
            apCollection.setEntryId(apBehaviorEntry.getId()); //行为实体ID
            apCollection.setArticleId(dto.getEntryId()); //文章ID
            apCollection.setType(dto.getType());//类型
            apCollection.setCreatedTime(new Date());
            apCollection.setUpdatedTime(new Date());
            save(apCollection);
        } else {
            if(dto.getOperation()==0){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已收藏不要重复收藏");
            }
            //5.如果存在就删除
            removeById(apCollection.getId());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
